package com.atguigu.gulimalltestssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping
    public String userInfo(@RequestParam("token") String token){
        return redisTemplate.opsForValue().get(token);
    }

    /**
     * @CookieValue获取当前域名下请求中的cookie
       为什么A服务登录后，B服务第一次访问会知道该用户已登录，是因为sso服务登录成功后会设置cookie，以后浏览器在访问sso域名时就会携带cookie
       所有就知道了该用户登录情况
     * @param redirectUrl
     * @param model
     * @param sso_token
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl,
                            Model model,@CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
            //说明之前有人登录过，浏览器留下了痕迹
            return "redirect:"+redirectUrl+"?token="+sso_token;
        }

        model.addAttribute("url",redirectUrl);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid,username);
            //保证当前的浏览器登录后留一个印记，以供当前浏览器的其他服务都不用再次登录
            Cookie cookie = new Cookie("sso_token",uuid);
            response.addCookie(cookie);
            //登录成功跳转回过来之前的页面
            return "redirect:"+url+"?token="+uuid;
        }
        //失败
        return "login";
    }
}
